<script setup lang="ts">
import { computed } from 'vue'
import { secondsToHms } from '@/utils/tools.ts'
import { storageLocal } from '@pureadmin/utils'
import { useGameStore } from '@/stores/modules/game'

import type { IChef, IRecipe } from '@/stores/types'
import type { IBestCombResult } from './types'

interface IItem {
  chef: IChef
  recipes: IRecipe[]
}

const props = defineProps<{
  data?: IBestCombResult
}>()

const { chefsMap, recipesMap } = useGameStore()
const localName = 'bestCombResult'
const localBestCombResult = storageLocal().getItem<IBestCombResult | null>(localName)
const bestCombResult = computed(() => {
  const result = props.data ?? localBestCombResult
  if (result) {
    storageLocal().setItem(localName, result)
  }
  return result
})

const totalRevenue = computed(() => bestCombResult.value?.totalRevenue ?? 0)
const workingTime = computed(() => {
  const time = bestCombResult.value?.workingTime ?? 0
  let result = time.toString()
  if (time > 0) {
    const hms = secondsToHms(time)
    result = `${hms.h}时${hms.m}分${hms.s}秒`
  }
  return result
})

const combination = computed(() => {
  const comb = bestCombResult.value?.combination ?? []
  const combInfo: IItem[] = []
  comb.forEach(({ chefId, cookable }) => {
    const recipes: IRecipe[] = []
    const chef = chefsMap.get(chefId)
    if (!chef) return
    cookable.forEach(({ recipeId }) => {
      const recipe = recipesMap.get(recipeId)
      if (!recipe) return
      recipes.push(recipe)
    })
    combInfo.push({ chef, recipes })
  })
  return combInfo
})
</script>

<template>
  <n-list bordered v-if="combination.length">
    <template #footer>
      <n-flex :size="24">
        <span>收益：{{ totalRevenue }}</span>
        <span>营业时间：{{ workingTime }}</span>
      </n-flex>
    </template>
    <n-list-item v-for="item in combination" :key="item.chef.chefId">
      <template #prefix>
        <n-button type="info" dashed>{{ item.chef.name }}</n-button>
      </template>
      <n-flex>
        <n-button dashed v-for="recipe in item.recipes" :key="recipe.recipeId">
          {{ recipe.name }}
        </n-button>
      </n-flex>
    </n-list-item>
  </n-list>
</template>
